JBoss Community Archive (Read Only)

GateIn Portal 3.4

RequireJS Integration

Introduction

Resource Management, appeared since the release 3.3.0-GA of GateIn, has seen nice management of JavaScript resources on the server side. However, the feature contains a gap as it does not support a real asynchronous loading on client side, that encouraged us to integrate the concept of Asynchronous Module Definition into GateIn.

RequireJS was selected from the matrix of AMD-compliant libraries.

How RequireJS works?

Let alpha.js be a JavaScript file whose content is in module definition format.

alpha.js
define("alpha", function(){
  var _module = {};

  _module.square = function(x){ return x*x; };

  return _module;
});

Consider a web page using RequireJS to access square method from alpha.js

<head>
...
<script type="text/javascript">
var require = {...., paths = {"alpha" : "path to alpha.js",...};
</script>

<script type="text/javascript">
  //RequireJS code
</script>
...
</head>
<body>

  <script type="text/javasript">
     require("alpha", function(alpha))
     {
       alert(alpha.square(10));
     };
  </script>
</body>

A JavaScript code block under <body> element requires alpha module, callback method passed to require asks the browser to display alpha.square(10) in an alert message. As the block is interpreted, there are two scenarios:

alpha.js has been loaded into browser

alpha object is created (if it does not exist) thanks to factory method.

Factory method
function(){
  var _module = {};

  _module.square = function(x){ return x*x; };

  return _module;
}

Once the alpha module is available, alpha.square(10) returns 10*10 = 100.

alpha.js has not been loaded into browser yet

RequireJS searches through require variable the file path associated with alpha, what it finds out is actually the path to alpha.js. Afterward, a <script> element loading alpha.js is auto generated under <head> and we are falling back to the first scenario.

Auto generated Red Hat, Inc.